<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件编辑器</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f4f4f4;
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        textarea {
            min-height: 300px;
            font-family: monospace;
        }
        button {
            display: block;
            width: 100%;
            padding: 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        .status {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>文件编辑器</h1>
        
        <div class="form-group">
            <label for="filename">文件名:</label>
            <input type="text" id="filename" placeholder="输入文件名 (如: index.html)">
            <div class="info status" id="filename-info">
                注意: 系统可能自动将长文件名转换为8.3格式 (如: INDEX~1.HTM)
            </div>
        </div>
        
        <div class="form-group">
            <label for="content">文件内容:</label>
            <textarea id="content" placeholder="输入文件内容..."></textarea>
        </div>
        
        <button id="save-btn">保存文件</button>
        
        <div class="status" id="status-msg"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const filenameInput = document.getElementById('filename');
            const contentTextarea = document.getElementById('content');
            const saveButton = document.getElementById('save-btn');
            const statusMsg = document.getElementById('status-msg');
            const filenameInfo = document.getElementById('filename-info');
            
            // 定义分段大小（字节）
            const CHUNK_SIZE = 1024;
            
            // 显示状态消息
            function showStatus(message, type) {
                statusMsg.textContent = message;
                statusMsg.className = 'status ' + type;
                statusMsg.style.display = 'block';
                
                // 5秒后自动隐藏
                setTimeout(() => {
                    statusMsg.style.display = 'none';
                }, 5000);
            }
            
            // 显示文件名提示
            filenameInfo.style.display = 'block';
            
            // 创建空白文件
            function createEmptyFile(filename) {
                return fetch('/api/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ filename: filename })
                }).then(response => response.json());
            }
            
            // 追加内容到文件
            function appendToFile(filename, content) {
                return fetch('/api/append', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        filename: filename,
                        content: content 
                    })
                }).then(response => response.json());
            }
            
            // 分段保存文件
            async function saveFileInChunks(filename, content) {
                // 首先创建空白文件
                const createResult = await createEmptyFile(filename);
                if (createResult.status !== 'success') {
                    throw new Error(`创建文件失败: ${createResult.message}`);
                }
                
                // 如果内容为空，直接返回成功
                if (!content) {
                    return { bytesWritten: 0 };
                }
                
                let totalBytesWritten = 0;
                
                // 分段追加内容
                for (let i = 0; i < content.length; i += CHUNK_SIZE) {
                    const chunk = content.substring(i, i + CHUNK_SIZE);
                    const appendResult = await appendToFile(filename, chunk);
                    
                    if (appendResult.status !== 'success') {
                        throw new Error(`追加内容失败: ${appendResult.message}`);
                    }
                    
                    totalBytesWritten += appendResult.bytesWritten;
                }
                
                return { bytesWritten: totalBytesWritten };
            }
            
            // 保存文件
            saveButton.addEventListener('click', async function() {
                const filename = filenameInput.value.trim();
                const content = contentTextarea.value;
                
                if (!filename) {
                    showStatus('请输入文件名', 'error');
                    return;
                }
                
                // 显示加载状态
                saveButton.textContent = '保存中...';
                saveButton.disabled = true;
                
                try {
                    // 使用分段保存函数
                    const result = await saveFileInChunks(filename, content);
                    showStatus(`文件保存成功: ${filename} (${result.bytesWritten} 字节)`, 'success');
                } catch (error) {
                    showStatus(`保存失败: ${error.message}`, 'error');
                } finally {
                    saveButton.textContent = '保存文件';
                    saveButton.disabled = false;
                }
            });
        });
    </script>
</body>
</html>